<!--
 * @Descripttion: 用户管理
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-21 14:43
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-09-27 15:19:21
-->
<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card class="box-card"
                 :body-style="{ overflowY: 'auto', height: '95%' }"
        >
          <div slot="header" class="clearfix">
            <i class="el-icon-menu orgIcon"></i>
            <span>组织机构</span>
<!--            <el-button style="float: right; padding: 3px 0" type="text">操作</el-button>-->
            <el-input style="margin-top: 10px;" v-model="filterText" placeholder="搜索" clearable></el-input>
          </div>
          <el-tree
              ref="space"
              :data="treeData"
              node-key="id"
              :check-on-click-node="true"
              :expand-on-click-node="true"
              :props="defaultProps"
              :filter-node-method="filterNode"
              @node-click="changeTree" lazy
            :load="loadNode">
             <span class="custom-tree-node" slot-scope="{ node }">
               <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start">
                <span>{{ node.label }}</span>
               </el-tooltip>
             </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card">
          <!-- 搜索 -->
          <e-control :search-form-options="formOptions"
                     :btns="btns"
                     @on-search="onSearch"
                     @on-insert="onInsert">
          </e-control>

          <!-- 表格 -->
          <el-table :data="tableData" border style="width: 100%" :max-height="maxHeightNow">
            <el-table-column prop="account" label="登录名" width="100"></el-table-column>
            <el-table-column prop="name" label="用户姓名" width="100"></el-table-column>
            <el-table-column prop="mobile" label="电话" width="150"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
            <el-table-column prop="roles" label="角色" width="180"></el-table-column>
<!--            <el-table-column prop="date" label="是否有效" width="180"></el-table-column>-->
            <el-table-column prop="orgName" label="组织" width="180"></el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="240">
              <template slot-scope="scope">
                <el-tooltip content="编辑"
                            placement="top">
                  <el-button type="warning"
                             size="mini"
                             icon="el-icon-document"
                             plain
                             @click="editorEvent(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除"
                            placement="top">
                  <el-button type="danger"
                             size="mini"
                             icon="el-icon-document-delete"
                             plain
                             @click="deleteUserEvent(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="选择角色"
                            placement="top">
                  <el-button type="primary"
                             size="mini"
                             icon="el-icon-bangzhu"
                             plain
                             @click="selectRole(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="重置密码"
                            placement="top">
                  <el-button type="warning"
                             size="mini"
                             icon="el-icon-refresh"
                             plain
                             @click="resetPassword(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalPage">
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>

    <!-- editDialog 新增用户 START -->
    <el-dialog
        title="分配角色"
        :visible.sync="dialogRoleVisible"
        width="30%"
        :before-close="handleRoleClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
      <div class="selectRole">
        <el-select v-model="setRole"
                   multiple
                   collapse-tags
                   placeholder="请选择角色">
          <el-option v-for="item in rolesArr"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- editDialog 编辑弹窗 START -->
    <el-dialog :title="editDialogTitle"
               :visible.sync="editDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :before-close="cancelDialogDataHandle"
               width="1000px"
              ref="dialog">
			  <div>
				  <el-tree
				      ref="space"
				      :data="treeData"
				      node-key="id"
				      :check-on-click-node="true"
				      :expand-on-click-node="true"
				      :props="defaultProps"
				      :filter-node-method="filterNode"
				      @node-click="changeTree2" lazy
				    :load="loadNode"
					style="float: left;width: 340px;"
					>
				     <span class="custom-tree-node" slot-scope="{ node }">
				       <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start">
				        <span>{{ node.label }}</span>
				       </el-tooltip>
				     </span>
				  </el-tree>
				  <div style="float: right;width: 550px;">
					  
					<el-form>
						<el-form-item label="组织/部门">
						{{orgName}}
						</el-form-item>
					</el-form>
					  <e-form ref="dialogForm"
					          :formOptions="editFormOptions"
					          :formDataCurrent="dialogFormCurrent"
					          :formRules="editFormRules"></e-form>
					  <span slot="footer"
					        class="dialog-footer">
					    <el-button @click="cancelDialogDataHandle">取 消</el-button>
					    <el-button type="primary"
					               @click="saveDialogDataHandle">确 定</el-button>
					  </span>
				  </div>
			  </div>
      
    </el-dialog>
    <!-- editDialog 编辑弹窗 END -->
  </div>
</template>

<script>
  import eControl from '@/components/e-control'
  import eForm from '@/components/e-form'
  import { formOptions, btns } from './control'
  import {editFormOptions, editFormRules} from './form'
  import interFaces from './interFaces'
  import { getOrgTree, getRoleAll, getUserList, deleteUser, userAddRole, resetPasswordApi,getOrgTreeLazy} from '@/api/admin.api'
  export default {
    name: 'users',
    components: {
      eControl,
      eForm
      // eManage
    },
    data() {
      return {
        formOptions,
        btns,
        // columns,
        editFormOptions,
        editFormRules,
        interFaces,
        dialogRoleVisible: false,
        editDialogShow: false,
        editDialogType: 0,
        setRole: '',
        // 编辑框表单数据
        dialogFormCurrent: {
          orgId:'',
          account:'',
          name:'',
          fax:'',
          email:'',
          tel:'',
          mobile:'',
          UKEY:'',
          status:''
        },
        // 左侧树
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        // 表格数据
        tableData: [],
        currentPage:1,
        pageSize:10,
        totalPage:0,
        rolesArr:[],   // 用户权限内的角色
        searchData:{},
        selectUserId: '',  // 选中用户的ID
        orgId: '', // 树型ID
        isOrg: true, // 编辑用户信息，检查是否绑定组织， true 没有组织，false 有组织
        filterText:'',
		newArr:[],
		orgName:''
      }
    },
    watch: {
      filterText(val) {
        this.$refs.space.filter(val)
      }
    },
    computed: {
      // 表单实例
      dialogForm () {
        return this.$refs.dialogForm
      },
      // 编辑框标题
      editDialogTitle () {
        return this.editDialogType === 0 ? '新增用户' : '编辑用户'
      },
      // 表格高度
      maxHeightNow () {
        const height = window.innerHeight
        return height -  290
      }
    },
    created() {},
    mounted() {
      // 查询权限内的角色
      this.queryRolesAll()
      this.getOrgTreeEvent()
      // 查询已注册用户
      this.getUserListEvent()
    },
    methods: {
		aa(t){
			console.log(t);
			var that = this;
			var s = '';
			if(t.length>1){
				s = t[t.length-1];
			}else{
				s = t;
			}
			getOrgTreeLazy(s).then((res) => {				
				res.forEach(item => {
					console.log(item);
					// 检查是否有叶子节点
					item['leaf'] = true
				})
				console.log("t---"+t.length);
				if(t.length == 1){
					that.treeData[0].children = [];
					that.treeData[0].children = res;
				}
				if(t.length == 2){
					that.treeData[0].children[0].children = [];
					that.treeData[0].children[0].children = res;
				}
				if(t.length == 3){
					that.treeData[0].children[0].children[0].children = [];
					that.treeData[0].children[0].children[0].children = res;
				}
			})
		},
      // 获取组织的ids
      collectId(data, id) {
        const list = []
        getAll(data, id)
        function getAll(data, id) {
          for (let i = 0 ; i < data.length ; i++) {
            const cur = data[i]
            const aa = findPnodeId(cur, id)
            if (aa && aa !== '0') {
              list.unshift(aa)
              getAll(data, aa)
            }
          }
        }
        function findPnodeId(data, id) {
          let result
          if (!data) {
            return
          }
          for (let i = 0 ; i < data.children.length ; i++) {
            const item = data.children[i]
            if (item.id === id) {
              result = data.id
              return result
            } else if (item.children && item.children.length > 0) {
              result = findPnodeId(item, id)
              if (result) {
                return result
              }
            }
          }
          return result
        }

        return [...list, id]
      },
      /**
       * @description 复合条件查询列表用户列表
       * @author 穆宏宇
       * @date 2020-09-24 13:34:09
       * @param
       * @return
       * */
      getUserListEvent(){
        const params = {
          size: this.pageSize,
          current: this.currentPage,
          account: this.searchData.account,
          name: this.searchData.name
        }
        if (this.orgId) {params['orgId'] = this.orgId}
        getUserList(params).then(res=>{
          this.tableData = res.records
          this.totalPage = res.total
        })
      },
      // 获取组织树
      getOrgTreeEvent(){
        getOrgTreeLazy('0').then(res=>{
          this.treeData = res
          this.$nextTick(()=>{
            this.$set(this.editFormOptions[0].props,'options',this.treeData)
          })
        }).catch(err =>{
          this.$message({
            message: err.msg,
            type: 'error'
          })
        })
      },
	  // 组织机构节点数据
	  loadNode(node, resolve) {
	  	if (node.level === 0) {
	  		getOrgTreeLazy('0').then((res) => {
	  			res.forEach(item => {
	  				// 检查是否有叶子节点
	  				item['leaf'] = false
	  			})
	  			if(res.length>0){
	  				this.form = res[0];
	  			}
	  			return resolve(res)
	  		})
	  	} else if (node.data.hasChildren) {
	  		getOrgTreeLazy(node.data.id).then((res) => {
	  			res.forEach(item => {
	  				// 检查是否有叶子节点
	  				item['leaf'] = !item.hasChildren
	  			})
	  			return resolve(res)
	  		})
	  	} else {
	  		return resolve([])
	  	}
	  
	  
	  },
      /**
       * @description 查询权限内的角色
       * @author 穆宏宇
       * @date 2020-09-24 09:19:23
       * @param
       * @return
       * */
      queryRolesAll(){
        getRoleAll().then((response) =>{
          this.rolesArr = response
        })
      },
      handleOther (data) {
        console.log(data)
      },
      changeTree(item) {
        this.orgId = item.id
        // 查询已注册用户
        this.getUserListEvent()
      },
      changeTree2(item) {
        this.orgId = item.id
		this.orgName = item.name
        // 查询已注册用户
      },
      //优化之后的代码 不管有几级都可以适用,不过用了递归
      filterNode(value, data, node) {
        console.log(value, data, node)
        if (!value) {
          return true
        }
        let _array = [] //这里使用数组存储 只是为了存储值。
        this.getReturnNode(node, _array, value)
        let result = false
        _array.forEach(item => {
          result = result || item
        })
        return result
      },
      getReturnNode(node, _array, value) {
        let isPass = node && node.label && node.label.indexOf(value) !== -1
        isPass ? _array.push(isPass) : ''
        if (!isPass && node.level != 1 && node.parent) {
          this.getReturnNode(node.parent, _array, value)
        }
      },
      handleRoleClose(done){
        done();
      },
      // 搜索
      onSearch(data) {
        // todo 清空条件
        this.currentPage = 1
        this.pageSize = 10
        this.searchData = data
        this.getUserListEvent()
      },
      // 新增
      onInsert () {
        const objOption =   {
          label: '密码',
          type: 'input',
          key: 'password',
          props: {
            placeholder: '请输入密码',
            type: 'password'
          }
        }

        this.editFormRules.password[0].required = true
        const arr = this.editFormOptions.filter(item=>item.label === '密码')
        if (arr.length <= 0) {
          this.editFormOptions.splice(2,0,objOption)
        }
        const tempTree = [...this.treeData]
        // 组织机构激活
        this.setTreeDisabled(tempTree,false)
        this.$set(this.editFormOptions[0].props,'options',tempTree)
        this.dialogFormCurrent = {}
        this.openDialog()
      },
      // 组织选项是否允许编辑
      setTreeDisabled(array,disabled) {
        if (array && array.length > 0) {
          array.forEach(item=>{
            item['disabled'] = disabled
            if ('children' in item) {
              this.setTreeDisabled(item.children,disabled)
            }
          })
        }
      },
      // 编辑
      editorEvent (rowData) {
        const curData = {...rowData}
        this.editFormRules.password[0].required = false
        this.editFormOptions = this.editFormOptions.filter(item =>item.label !== '密码')
        const tempTree = [...this.treeData]
        if (curData.orgId && curData.orgId !== null) {
          // 组织禁用
          this.setTreeDisabled(tempTree,false)
          this.$set(this.editFormOptions[0].props,'options',tempTree)
          // 查找组织机构父级及本级id
          curData.orgId = this.collectId(tempTree,curData.orgId)
          this.isOrg = false
        } else {
          // 组织机构激活
          this.setTreeDisabled(tempTree,false)
          this.$set(this.editFormOptions[0].props,'options',tempTree)
        }
        this.dialogFormCurrent = curData
        this.openDialog(1)

      },
      // 删除
      deleteUserEvent(rowData) {
        this.$confirm('确定要删除该用户吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser(rowData.id).then(()=>{
            this.getUserListEvent()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 每页显示条数
      handleSizeChange(val) {
        this.pageSize = val
        this.getUserListEvent()
      },
      // 当前页数
      handleCurrentChange(val) {
        this.currentPage = val
        this.getUserListEvent()
      },
      // 选择角色
      selectRole(rowData) {
        this.setRole = rowData.roleIds ? rowData.roleIds.split(',') : []
        this.selectUserId = rowData.id
        this.dialogRoleVisible = true
      },
      // 确定已选角色
      confirmRole () {
        userAddRole({roleIds: this.setRole , userIds:[this.selectUserId]}).then( ()=>{
          this.dialogRoleVisible = false
          this.getUserListEvent()
        })
      },
      // 重置密码
      resetPassword (data) {
        resetPasswordApi(data.id).then(()=>{
          this.$message.success('重置成功')
        })
      },
      /**
       * @functionName openDialog
       * @param {Number} type 编辑框类型;0:新增;1:编辑;
       * @description 打开编辑框
       * @author 张航
       * @date 2020-09-08 11:38:51
       * @version V1.0.0
       */
      openDialog (type = 0) {
        this.editDialogType = type
        this.editDialogShow = true
      },
      /**
       * @functionName closeDialog
       * @description 关闭编辑框
       * @author 张航
       * @date 2020-09-08 14:27:02
       * @version V1.0.0
       */
      closeDialog () {
        this.editDialogType = 0
        this.editDialogShow = false
      },
      /**
       * @functionName cancelDialogData
       * @description 取消保存弹框数据
       * @author 张航
       * @date 2020-09-08 18:17:11
       * @version V1.0.0
       */
      cancelDialogDataHandle () {
        this.dialogForm.handleRefresh()
        this.closeDialog()
      },
      /**
       * @functionName saveDialogData
       * @description 保存弹框数据
       * @author 张航
       * @date 2020-09-08 18:15:14
       * @version V1.0.0
       */
      saveDialogDataHandle () {
        // 表单验证
        let check = ''
        this.$refs.dialogForm.handleValidate( v => {
          check = v
        })
        if (!check) {
          return check
        }
        const data = this.$refs.dialogForm.formData
		data.orgName = bbb;

        if (this.editDialogType === 0) {
          var regu =/^(?=.*?\d)(?=.*?[A-Za-z])[\dA-Za-z]{8,}$/;
          var re = new RegExp(regu);
          if (!re.test(data.password)) {
            this.$message({
              message: '密码必须（字母+数字）最少8位',
              type: 'warning'
            })
            return
          }
        }

        // 定义请求地址
        const _url = this.editDialogType === 0
          ? this.interFaces.insert.url
          : this.interFaces.update.url
        // 定义请求类型
        const _type = this.editDialogType === 0
          ? this.interFaces.insert.type
          : this.interFaces.update.type


        if (this.editDialogType === 0 || this.isOrg) {
          data.orgId = (data.orgId instanceof Array) ? data.orgId.pop() : data.orgId
        } else {
          if('orgId' in  data) {
            delete data['orgId']
          }
        }

        this.interFaceEvent(_url, data, _type).then(() => {
          this.dialogForm.handleRefresh()
          this.closeDialog()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.getUserListEvent()
        })
      },
      /**
       * @functionName interFaceEvent
       * @param {String|} url 请求地址
       * @param {Object} data 请求参数
       * @param {String} type 请求类型，默认为GET
       * @return {Promise} 返回结果
       * @description 接口访问
       * @author 张航
       * @date 2020-09-14 16:14:51
       * @version V1.0.0
       */
      interFaceEvent (url, data, type = 'GET') {
        let _url = url
        const _type = type.toLowerCase()
        if (_type === 'get') {
          _url = _url + this.$tools.urlParam(data)
        }
        return this.$api[_type](_url, data)
      }
    }
  }
</script>

<style scoped lang="scss">
.box-card {
  margin: 4px;
  height: calc(100vh - 120px);
  .el-card__body {
    padding: 0;
  }
  .el-table {
    margin-top: 20px;
  }
  .el-pagination {
    text-align: right;
  }
}
/*.abc-header {*/
/*  color: #0000ff;*/
/*}*/
/*.abc {*/
/*  font-weight: bold;*/
/*  color: #e53939;*/
/*}*/
.selectRole {
  padding: 30px;
  box-sizing: border-box;
  .el-select {
    width: 100%;
  }
}
::v-deep .el-tree>.el-tree-node{
  min-width:100%;
  display:inline-block;
  overflow: auto;
}
</style>
<style lang="css">

  .el-tooltip__popper,.el-tooltip__popper.is-dark{
    background: #FFFFFF;
    max-width: 400px;
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    padding: 12px;
    color: black;
    line-height: 180%;
    -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  .el-tooltip__popper[x-placement^=top] .popper__arrow {
    bottom: -6px;
    left: 50%;
    margin-right: 3px;
    border-top-color: #FFFFFF;
    border-bottom-width: 0;
    -webkit-filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.1));
    filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
  }
  .el-tooltip__popper[x-placement^=top] .popper__arrow:after {
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
  }
</style>


